package com.huawei.codecheck.uccp.plugin.cangjie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.*;

public class ExecUtils {

    public static HashMap<String, String> ENV_MAP = new HashMap<>();
    protected static final Logger LOG = LoggerFactory.getLogger(ExecUtils.class);
    public static int run(String[] cmdarray) {
        try {
            ProcessBuilder pb = new ProcessBuilder(cmdarray);
            Map<String, String> environment = pb.environment();
            environment.clear();
            environment.putAll(ENV_MAP);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            int exitcode = process.waitFor();
            return exitcode;
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error(e.toString());
            return 1;
        }
    }

    public static void setCangjiePath(String path){
        String arch = System.getProperty("os.arch");
        Map<String, String> env = System.getenv();
        if (env.get("CANGJIE_HOME") != null) {
            return;
        }
        ENV_MAP.put("CANGJIE_HOME", path);
        String env_path = env.get("PATH");
        ArrayList<String> paths = new ArrayList<String>();
        paths.add(path + File.separator + "bin");
        paths.add(path + File.separator + "tools" + File.separator + "bin");
        paths.add(env_path);
        String new_Path = String.join(":", paths);
        paths.clear();
        paths.add(String.join(File.separator,new String[]{path, "runtime", "lib", "linux_"+ arch + "_llvm"}));
        paths.add(String.join(File.separator,new String[]{path, "libext"}));
        if (env.get("LD_LIBRARY_PATH") != null) {
            paths.add(env.get("LD_LIBRARY_PATH"));
        }

        String new_LD_LIBRARY_PATH = String.join(":", paths);

        env.forEach((k,v) -> {
            if ("PATH".equals(k)) {
                ENV_MAP.put("PATH", new_Path);
            }else if ("LD_LIBRARY_PATH".equals(k)) {
                ENV_MAP.put("LD_LIBRARY_PATH", String.join(":", new_LD_LIBRARY_PATH));
            } else{
                ENV_MAP.put(k,v);
            }
        });
    }
}
